iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0
佛心分享-刷題不只是刷題

轉生理工組後從零開始的leetcode刷題系列 第 6

day-6[easy.1893]check if all the integers in a range are covered

  • 分享至 

  • xImage
  •  

You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi.

Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise.

An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi.


  • inclusive =涵蓋
    題目大意是要確認[left,right]中一連串的整數數字是否涵蓋在題目給予的一系列ranges中。
    我個人的解題思路是
  1. 把[left,right]包含的數字都先列出來
  2. 清點是否[left,right]中所有數字都有被ranges的區間涵蓋
    但總覺得這樣的解法有點暴力、費時,不過我目前沒有別的思路,
    先寫出自己的程式再去參考別人的作法好了...

基本就是用兩個for迴圈,
第一個用來遍歷[left,right]包含的數字;第二個針對該數字檢查是否包含在ranges內
public boolean isCovered(int[][] ranges, int left, int right) {
// 第一個
for (int i = left; i <= right; i++) {
// 做一個布林值檢查有沒有被涵蓋
boolean covered = false;

        // 第二個
        for (int[] range : ranges) {
            int start = range[0];
            int end = range[1];
            // 如果一旦被涵蓋就不用再檢查其他區間
            if (i >= start && i <= end) {
                covered = true;  
                break;  
              }
         }
         if (!covered) {
            return false;
         }
    }
    // 如果所有數字都被涵蓋,返回true
    return true;
}

丟去leetcode檢查答案
https://ithelp.ithome.com.tw/upload/images/20240921/201694323SUF9aRyyt.png
成功了,結束這回合!


後來有去看其他人的解法,幾乎都是大同小異的,
也許這已經是最簡單解了?


上一篇
day-5[easy.1913]maximum product difference between two pairs
下一篇
day-7[easy.1952]three divisors
系列文
轉生理工組後從零開始的leetcode刷題12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言